﻿@inject DbService DbService
@inject GlobalNotificationService GlobalNotificationService
@inject LanguageService LanguageService
@inject IStringLocalizerFactory LocalizerFactory
@using Microsoft.Extensions.Localization

<div class="relative p-6 sm:p-8 bg-white dark:bg-gray-700 rounded-lg sm:shadow-xl max-w-md w-full mx-auto">
    <div class="text-center">
        <div class="space-y-4">
            <BoldLoadingIndicator />
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white">@Localizer["WelcomeTitle"]</h2>
            <p class="text-sm text-gray-500 dark:text-gray-400">
               @Localizer["CreatingDescription"]
            </p>

            <div>
                @if (ErrorMessage.Length > 0)
                {
                    <AlertMessageError Message="@ErrorMessage" />
                }
            </div>
        </div>
    </div>
</div>

@code {
    private IStringLocalizer Localizer => LocalizerFactory.Create("Pages.Main.Sync.StatusMessages.Creating", "AliasVault.Client");
    private string ErrorMessage { get; set; } = string.Empty;
    private bool IsMigrating { get; set; } = false;

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
    }

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            // Start the database migration process
            await MigrateDatabase();
        }
    }

    /// <summary>
    /// Migrate (create) the database and upload it to the server.
    /// </summary>
    private async Task MigrateDatabase()
    {
        // Simulate a delay.
        await Task.Delay(1000);

        // Migrate (create) the database.
        if (await DbService.CreateNewVaultAsync())
        {
            try
            {
                // Initialize vault settings with user's browser language preference. This also automatically
                // saves the new empty database to the server.
                await InitializeVaultSettings();

                // Migration successful, update state which will trigger the status message UI to refresh and redirect user.
                DbService.GetState().UpdateState(DbServiceState.DatabaseStatus.Ready);
                return;
            }
            catch
            {
                // Migration failed
                ErrorMessage = Localizer["SaveFailedError"];
            }
        }
        else
        {
            // Migration failed
            ErrorMessage = Localizer["CreationFailedError"];
        }

        StateHasChanged();
    }

    /// <summary>
    /// Initialize vault settings with user preferences detected from the browser.
    /// </summary>
    private async Task InitializeVaultSettings()
    {
        try
        {
            // Get the current browser language preference
            var browserLanguage = await LanguageService.GetCurrentLanguageAsync();

            // Set the AppLanguage setting in the vault to match the browser preference
            await DbService.Settings.SetAppLanguage(browserLanguage);
        }
        catch (Exception ex)
        {
            // Log the error but don't fail the vault creation process
            // The language can be changed later by the user if needed
            Console.WriteLine($"Warning: Failed to initialize language setting: {ex.Message}");
        }
    }
}
